//
//  KLLoginViewController.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 16/4/19.
//  Copyright © 2016年 陈宾鹏. All rights reserved.
//

#import "KLLoginViewController.h"
#import "KLRegisterViewController.h"
#import "KLFindPasswordViewController.h"
#import "KLHttpAPI.h"
#import "KLHelp.h"
#import "JRToast.h"
#import "KLOpenClockViewController.h"
#import "KLLeftTableViewController.h"
#import "MMDrawerController.h"
#import "MMdrawerVisualState.h"
#import "FMDBTool.h"
#import "KLManualTableViewController.h"
#import "KLApplyKeysMsgTableViewController.h"
#import "KLTabBarVC.h"

@interface KLLoginViewController ()<UITabBarControllerDelegate>
{
    KLManualTableViewController *manualOpenLcok;
    KLApplyKeysMsgTableViewController *applyKeysMsgVC;
}

@property (weak, nonatomic) IBOutlet UILabel *userNameOrPhoneNumberLabel;
@property (weak, nonatomic) IBOutlet UITextField *userNameOrPhoneNumberField;
@property (weak, nonatomic) IBOutlet UITextField *passWordField;
@property (weak, nonatomic) IBOutlet UIButton *rememberPassWord;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@property (assign) NSInteger isHaveNet;
@property (strong,nonatomic) NSUserDefaults *userDefaults;
@property (nonatomic,strong) UIWindow *window;
@property (nonatomic,strong) MMDrawerController *drawerController;
@end

static NSArray *_dateBaseArray;

@implementation KLLoginViewController

-(NSUserDefaults *)userDefaults{
    if(!_userDefaults){
        _userDefaults = [NSUserDefaults standardUserDefaults];
    }
    
    return _userDefaults;
}

-(UIWindow *)window{
    if(!_window){
        _window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
        [_window makeKeyAndVisible];
    }
    return  _window;
}

-(void)viewWillAppear:(BOOL)animated{
    //检查网络状况
    if([KLHelp isConnectionAvailable] == 0){
        self.isHaveNet = 0;
        [JRToast showWithText:@"您当前处在无网状态下" bottomOffset:50 duration:1.5];
    }else{
        self.isHaveNet = 1;
    }
    
    //将底层帐号显示在textfield上
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    self.userNameOrPhoneNumberField.text = [userDefault objectForKey:@"phoneNumber"];
    self.userNameOrPhoneNumberField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    //创建注册按钮
    [self createRegisterButton];
    
    //获取记住密码的状态
    NSString *isRememberPassword = [self.userDefaults stringForKey:@"isRememberPassword"];
    if([isRememberPassword isEqualToString:@"YES"] || isRememberPassword == nil){
        [self.rememberPassWord setBackgroundImage:[UIImage imageNamed:@"R单选框已选中"] forState:UIControlStateNormal];
        self.rememberPassWord.tag = 11;
        self.passWordField.text = [userDefault objectForKey:@"password"];
        self.passWordField.clearButtonMode = UITextFieldViewModeWhileEditing;
        
    }else{
        [self.rememberPassWord setBackgroundImage:[UIImage imageNamed:@"R单选框未选中"] forState:UIControlStateNormal];
        self.rememberPassWord.tag = 10;
    }
    
    //登录按钮美化
    [self.loginBtn setBackgroundColor:[UIColor colorWithRed:(float)8/255 green:(float)128/255 blue:(float)181/255 alpha:1]];
    self.loginBtn.layer.cornerRadius = 5;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //是否有新的申请
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(isHaveNewApply:) name:@"isHaveNewApply" object:nil];
    _dateBaseArray = [NSArray arrayWithObjects:@"userid",@"username",@"email",@"password",@"nickname",@"mobile",@"avatar",@"validflag",@"score",@"feeaccount",@"deviceid",@"devicetype",@"lastloginversion",@"lastlogintime",@"imgurl0",@"imgurl1",@"state",@"birthday",@"imgurl2",@"sex",@"token",nil];
    
    //设置导航栏
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:21]}];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:(float)8/255 green:(float)128/255 blue:(float)181/255 alpha:1];
    [self.navigationController.navigationBar setTranslucent:NO];
    self.navigationItem.title = @"登录";
}-(void)isHaveNewApply:(NSNotification *)notify{
    NSDictionary *userInfo = [notify userInfo];
    NSString *new_order = [userInfo objectForKey:@"newApplyCount"];
    if(new_order.integerValue != 0){
        [applyKeysMsgVC.tabBarItem setBadgeValue:new_order];
    }
}

//初始化注册按钮
-(void)createRegisterButton{
    UIButton * resgisterBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44.0f, 44.0f)];
    [resgisterBtn setTitle:@"注册" forState:UIControlStateNormal];
    [resgisterBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [resgisterBtn.titleLabel setTextAlignment:NSTextAlignmentCenter];
    [resgisterBtn addTarget:self action:@selector(registerButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *resgisterBtnItem = [[UIBarButtonItem alloc] initWithCustomView:resgisterBtn];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
    [resgisterBtnItem setStyle:UIBarButtonItemStyleBordered];
#pragma clang diagnostic pop
    
    [self.navigationItem setRightBarButtonItem:resgisterBtnItem];
}-(void)registerButtonClick:(UIButton *)sender{
    //跳转至注册页面
    KLRegisterViewController *registerVC = [[KLRegisterViewController alloc]init];
    [self.navigationController pushViewController:registerVC animated:YES];
}

- (IBAction)rememberPwd:(UIButton *)sender {
    if(self.rememberPassWord.tag == 10){
        [self.rememberPassWord setBackgroundImage:[UIImage imageNamed:@"R单选框已选中"] forState:UIControlStateNormal];
        self.rememberPassWord.tag = 11;
        [self.userDefaults setObject:@"YES" forKey:@"isRememberPassword"];
    }else if(self.rememberPassWord.tag == 11){
        [self.rememberPassWord setBackgroundImage:[UIImage imageNamed:@"R单选框未选中"] forState:UIControlStateNormal];
        self.rememberPassWord.tag = 10;
        [self.userDefaults setObject:@"NO" forKey:@"isRememberPassword"];
    }
}

//点击登录
- (IBAction)Loggin:(UIButton *)sender {
    //检查网络状况
    if([KLHelp isConnectionAvailable] == 0){
        self.isHaveNet = 0;
    }else{
        self.isHaveNet = 1;
    }
    //点击登录
    NSString *userName = self.userNameOrPhoneNumberField.text;
    NSString *passWord = self.passWordField.text;
    
    if(userName.length == 0){
        [KLHelp showTextHUDforView:self.view text:@"账号不能为空"];
        return ;
    }else if(passWord.length == 0){
        [KLHelp showTextHUDforView:self.view text:@"密码不能为空"];
        return ;
    }
    
    if(self.isHaveNet == 0){
        //无网状态下验证用户信息
        NSString *upPassword = self.passWordField.text;
        NSString *belowPassword = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"];
        NSString *userNmaeOrPhone = self.userNameOrPhoneNumberField.text;
        NSString *phone = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"];
        if([upPassword isEqualToString:belowPassword] && [phone isEqualToString:userNmaeOrPhone]){
            //跳转到主界面
            [self initMainViewController];
        }else{
            [JRToast showWithText:@"密码不正确"];
        }
    }else{
        [KLHelp showHUDAddedTo:self.view title:@"请稍候..." details:nil animated:YES];
        [KLHttpAPI requestLoginResultWithUsername:userName password:passWord completionHandler:^(NSString *responseString) {
            NSDictionary *responseDic = [KLHelp dictionaryWithJsonString:responseString];
            NSDictionary *inforDic = [responseDic objectForKey:@"infor"][0];
            
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            
            NSString *isTrue = [responseDic objectForKey:@"success"];
            if(isTrue.integerValue == 1){
                //将得到的用户信息存入数数据库
                [FMDBTool openDataBase];
                [FMDBTool deleteDataBase];
                for (int i = 0; i < _dateBaseArray.count; i++) {
                    if(i == 0){
                        [FMDBTool insertDataBaseWithKey:_dateBaseArray[i] value:[inforDic objectForKey:@"id"]];
                    }else{
                        [FMDBTool insertDataBaseWithKey:_dateBaseArray[i] value:[inforDic objectForKey:[_dateBaseArray objectAtIndex:i]]];
                    }
                }
                
                //拿到登录信息的数据
                NSMutableDictionary *userInfofDic = [FMDBTool selectDataBase];
                
                NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
                [userDefault setObject:[userInfofDic objectForKey:@"token"] forKey:@"token"];
                [userDefault setObject:[userInfofDic objectForKey:@"username"] forKey:@"userName"];
                [userDefault setObject:[userInfofDic objectForKey:@"mobile"] forKey:@"phoneNumber"];
                [userDefault setObject:[userInfofDic objectForKey:@"userid"] forKey:@"userid"];
                [userDefault setObject:self.passWordField.text forKey:@"password"];
                //跳转到主界面
                [self initMainViewController];
            }else{
                [JRToast showWithText:[responseDic objectForKey:@"msg"] bottomOffset:UI_View_Height/2 duration:1.5];
            }
        } errorHandler:^(NSString *error) {
            NSLog(@"返回失败:%@",error);
            [KLHelp hideAllHUDsForView:self.view animated:YES];
            [JRToast showWithText:@"网络异常,登陆超时!" bottomOffset:UI_View_Height/2 duration:1.5];
        }];
    }
}

//点击忘记密码
- (IBAction)findPassword:(id)sender {
    //跳转至找回密码页面
    KLFindPasswordViewController *findPasswordVC = [[KLFindPasswordViewController alloc]init];
    [self.navigationController pushViewController:findPasswordVC animated:YES];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

//跳转到主界面
-(void)initMainViewController{
    [self.view endEditing:YES];
    
    //初始化tabBarController
    UITabBarController *tabBarVC = [KLTabBarVC sharedTabBarVC];
    
    self.window.rootViewController = tabBarVC;
    [self.window makeKeyAndVisible];
}
@end
